/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ilookinto.jr;

import java.io.PrintWriter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.observation.Event;
import javax.jcr.observation.ObservationManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.commons.codec.binary.Base64;
import org.apache.jackrabbit.j2ee.RepositoryAccessServlet;
import org.apache.log4j.Logger;
import org.ilookinto.doexe.Processor;
import org.ilookinto.util.GlobalVar;

/**
 *
 * @author Administrator
 */
public class MetadataServlet extends HttpServlet {

  static String auth;
  Processor.Pair<PrintWriter, Scanner, Scanner> pair;
  Repository rep;
  static Session jcrSession;
  static ObservationManager observationManager;
  boolean shutdown = false;
  public static ExecutorService es = Executors.newFixedThreadPool(10);

  static {

    String name = "admin";
    String password = "admin";
    String authString = name + ":" + password;
    System.out.println("auth string: " + authString);
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    auth = new String(authEncBytes);
    //System.out.println("Base64 encoded auth string: " + authStringEnc);
  }
  Logger log = Logger.getLogger(MetadataServlet.class);

  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    String exe = this.getServletContext().getRealPath("/") + "WEB-INF\\resources\\2RTF";
    try {

      pair = Processor.processing(new String[]{exe});
      rep = RepositoryAccessServlet.getRepository(getServletContext());
      jcrSession = rep.login(new SimpleCredentials(GlobalVar.InternalUser, GlobalVar.InternalPassword.toCharArray()));
      observationManager =
              jcrSession.getWorkspace().getObservationManager();
      observationManager.addEventListener(new MetadataListener(jcrSession, pair, this.getServletContext().getRealPath("/") + "data\\"),
              Event.NODE_ADDED | Event.NODE_REMOVED | Event.NODE_MOVED | Event.PROPERTY_CHANGED, "/", true, null, 
              new String[]{"nt:file", "nt:unstructured"}, true);


      new Thread() {

        public void run() {
          while (pair.second.hasNextLine() && !shutdown) {
            System.out.println("process out=" + pair.second.nextLine());
          }
          /*while (pair.third.hasNextLine()) {
          System.out.println("process error out" + pair.third.nextLine());
          }*/
        }
      }.start();

      new Thread() {

        public void run() {

          while (pair.third.hasNextLine() && shutdown) {
            System.out.println("process error out" + pair.third.nextLine());
          }
        }
      }.start();

      System.out.println("ini....");
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }

  public void destroy() {

    System.out.println("desroying");
    try {
      //DriverManager.getConnection("jdbc:derby:;shutdown=true");
    } catch (Exception e) {
      e.printStackTrace();
    }
     System.out.println("db shut down?");
    es.shutdownNow();
    if (pair != null) {
      pair.first.write("Q\n");
      pair.first.close();
    }
    shutdown = true;
    System.out.println("desroyed");
    if (jcrSession != null) {
      jcrSession.logout();
      //System.exit(1);
    } else {
      System.out.println("wrong....");
    }
  }
}
